# -*- coding:utf-8 -*-
import os
from typing import Optional

import openpyxl


class ExcelUtil:


    def readDatas(self,file_name,sheetname=None):
        workbook = openpyxl.load_workbook(file_name)
        if sheetname==None:
            sheetnames = workbook.sheetnames
            sheetname=sheetnames[0]
        sheet = workbook[sheetname]
        result=[]
        for row in sheet.iter_rows(values_only=True):
            result.append(row)
        return result

    def readDatasAsDict(self,file_name,sheetname=None,keys=None):
        datas = self.readDatas(file_name, sheetname)
        if keys==None or len(keys)==0:
            return datas
        result=[]
        for data in datas:
            tmp={}
            for index, value in enumerate(keys):
                tmp[value] = data[index]
            tmp['companyNo']=str(tmp['riskCode'])[0:4]
            result.append(tmp)
        return result



class FileClient(object):
    def __init__(self,file_path=''):
        self.file_path=file_path
        self.excel_util = ExcelUtil()

    def write(self,file_path, line, split='\n'):  # 写入单条数据
        """写入一个数据"""
        with open(file_path, 'a',encoding='utf8') as file:
            file.write(str(line) + split)

    def write_list(self,file_path, line_list: list, mode='a', line_split="\n"):  # 写入一个列表
        if isinstance(line_list, list):
            with open(file_path, mode=mode) as file:
                for line in line_list:
                    file.write(str(line) + line_split)
        else:
            raise TypeError("write object needs type list")

    def del_file(self,file_path=None,file_paths=None):
        if file_path!=None:
            if os.path.exists(file_path):
                os.remove(file_path)
        if file_paths!=None and len(file_paths)>0:
            for tmp_file_path in file_paths:
                if os.path.exists(tmp_file_path):
                    os.remove(tmp_file_path)

    def read(self,path):
        self.file_path=path
        with open(self.file_path, "r", encoding='utf8') as file:
            lines = file.readlines()  # 按行读取文件内容
            result=[line.strip() for line in lines]
        return result

    def madir_folder(self,folder_path):
        # 创建文件夹路径
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)


    def get_all_files(self,path):
        file_list = []
        for root, dirs, files in os.walk(path):
            for file in files:
                file_list.append(os.path.join(root, file))
        return file_list

    def basename(self,path):
        file_name = os.path.basename(path)
        return file_name




